import { useEffect } from 'react';
import { useAppDispatch, useAppSelector } from '../store';
import {
  todoDelByIdAction,
  todoSingleAction,
  todoAllCheckedAction,
} from '../store/action/todo';

export default function Main() {
  const dispatch = useAppDispatch();
  const { lists, type } = useAppSelector((state) => state.todo);

  useEffect(() => {
    localStorage.setItem('todo-lists', JSON.stringify(lists));
    localStorage.setItem('todo-type', type);
  }, [lists, type]);

  const showList = lists.filter((item) => {
    if (type === 'active') return !item.isDone;
    if (type === 'completed') return item.isDone;
    return item;
  });

  let isCheckedAll = lists.length > 0 && lists.every((item) => item.isDone);

  return (
    <section className="main">
      <input
        id="toggle-all"
        className="toggle-all"
        type="checkbox"
        //   dispatch(todoAllCheckedAction(e))
        onChange={(e) => dispatch(todoAllCheckedAction(e.target.checked))}
        checked={isCheckedAll}
      />
      <label htmlFor="toggle-all">全选</label>
      {/* // 2.3 列表渲染任务 */}
      <ul className="todo-list">
        {showList.map((item: any) => (
          // 2.4 动态class的设置
          <li className={item.isDone ? 'completed' : ''} key={item.id}>
            <div className="view">
              <input
                className="toggle"
                type="checkbox"
                //  3.3 Main中选框触发回调
                onChange={() => dispatch(todoSingleAction(item.id))}
                // 💥 记得添上checked属性
                checked={item.isDone}
              />
              <label>{item.task}</label>

              <button
                className="destroy"
                // 4.3 点击触发回调
                onClick={() => dispatch(todoDelByIdAction(item.id))}
              ></button>
            </div>
          </li>
        ))}
      </ul>
    </section>
  );
}
